package com.xq.shop.service.admin.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xq.shop.dao.IBaseDAO;
import com.xq.shop.dao.ICategoryDAO;
import com.xq.shop.dao.ICategoryParamDAO;
import com.xq.shop.po.Category;
import com.xq.shop.po.CategoryParam;
import com.xq.shop.service.admin.ICategoryService;

@Service("admin_category_service")
public class CategoryService extends BaseService<Category> implements ICategoryService {

	@Autowired
	private ICategoryDAO categoryDAO;
	
	@Autowired
	private ICategoryParamDAO categoryParamDAO;
	
	@Override
	public IBaseDAO<Category> getDAO() {
		return categoryDAO;
	}
	
	@Override
	public List<Category> getByPID(long pID) {
		return categoryDAO.getByPID(pID);
	}

	@Override
	public void saveOrUpdate(Category instance) {
		
		if(instance.getParent_id() == 0L){
			instance.setGrade(Category.Grade1);
		} else {
			instance.setGrade(Category.Grade2);
		}
		
		if(instance.getParams() != null && instance.getParams().size() > 0){
		
			List<CategoryParam> list = new ArrayList<CategoryParam>();
			for(CategoryParam param : instance.getParams()){
				
				if(param.getName() == null ||
						StringUtils.isBlank(param.getName().trim())) continue;
				list.add(param);
			}
			instance.setParams(list);
		}
		categoryDAO.saveOrUpdate(instance);
		categoryParamDAO.deleteByCategoryID(null);
	}

	@Override
	public void delete(List<Long> ids) {
		super.delete(ids);
		for(Long id : ids){
			categoryParamDAO.deleteByCategoryID(id);
		}
	}
}
